/**
 * 统一网络请求封装
 * 处理请求拦截、响应拦截、错误处理
 */

interface RequestOptions {
  url: string;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  data?: any;
  header?: any;
  showLoading?: boolean;
  loadingText?: string;
  params?: any;
}

interface ResponseData {
  code: number;
  data: any;
  msg?: string;
  message?: string;
}

export const request = <T = any>(options: RequestOptions): Promise<T> => {
  return new Promise((resolve, reject) => {
    // 显示加载提示
    if (options.showLoading !== false) {
      uni.showLoading({
        title: options.loadingText || '加载中...',
        mask: true
      });
    }

    // 获取 token
    const token = uni.getStorageSync('token');

    // 设置默认请求头
    const header = {
      'Content-Type': 'application/json',
      ...options.header
    };

    // ⭐ 关键修改:若依框架需要 Bearer 前缀
    if (token) {
      header['Authorization'] = `Bearer ${token}`;
    }

    //处理get请求的params
    let url = options.url;
    if (options.params && Object.keys(options.params).length > 0) {
      const queryString = Object.keys(options.params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(options.params[key])}`)
        .join('&');
      url = `${url}?${queryString}`;
    }

    uni.request({
      url,
      method: options.method || 'GET',
      data: options.data,
      header,
      success: (res: any) => {
        // 打印完整响应信息,方便调试
        console.log('=== 请求成功 ===');
        console.log('URL:', url);
        console.log('状态码:', res.statusCode);
        console.log('响应数据:', res.data);
        console.log('===============');

        const responseData = res.data as ResponseData;

        // 根据状态码处理
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 后端返回格式: { code: 200, data: xxx, msg: '' }
          if (responseData.code === 200 || responseData.code === 0) {
            // 如果 data 存在则返回 data,否则返回整个响应
            resolve(responseData.data !== undefined ? responseData.data : responseData);
          } else if (responseData.code === 401) {
            // 处理业务层面的 401 错误
            uni.removeStorageSync('token');
            uni.removeStorageSync('userInfo');
            uni.showToast({
              title: responseData.msg || '登录已过期,请重新登录',
              icon: 'none'
            });
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/login/login'
              });
            }, 1500);
            reject(new Error(responseData.msg || '未授权'));
          } else {
            // 业务错误
            const errorMsg = responseData.msg || responseData.message || '请求失败';
            uni.showToast({
              title: errorMsg,
              icon: 'none',
              duration: 2000
            });
            reject(new Error(errorMsg));
          }
        } else if (res.statusCode === 401) {
          // HTTP 401 未授权,清除登录信息并跳转到登录页
          uni.removeStorageSync('token');
          uni.removeStorageSync('userInfo');
          uni.showToast({
            title: '登录已过期,请重新登录',
            icon: 'none'
          });
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/login/login'
            });
          }, 1500);
          reject(new Error('未授权'));
        } else {
          // 其他错误
          const errorMsg = responseData.msg || responseData.message || `请求失败: ${res.statusCode}`;
          uni.showToast({
            title: errorMsg,
            icon: 'none',
            duration: 2000
          });
          reject(new Error(errorMsg));
        }
      },
      fail: (err) => {
        console.error('=== 请求失败 ===');
        console.error('URL:', options.url);
        console.error('错误信息:', err);
        console.error('===============');
        
        uni.showToast({
          title: '网络连接失败',
          icon: 'none',
          duration: 2000
        });
        reject(err);
      },
      complete: () => {
        // 隐藏加载提示
        if (options.showLoading !== false) {
          uni.hideLoading();
        }
      }
    });
  });
};